<?php
/**
 * Created by PhpStorm.
 * User: dust2
 * Date: 14-12-21
 * Time: 上午12:07
 */
class Address extends Eloquent
{
    protected $table = 'addresses';

    protected $guarded = array('id');


    public  static function getDistrictByThirdId($id)
    {
        $addresses = ['region', 'city', 'province'];
        $district = [];
        for ($i = 0; $i <3; $i++) {
            $district[$addresses[$i]] = Linkage::getAddressById($id);
            $id = Linkage::getSuperId($id);
        }

        return $district;
    }

    public   static function getBaseInfo($user_id, $all = true, $check = 0)
    {
        $columns = ['id', 'name', 'location', 'phone', 'postcode', 'default', 'third_level'];
        return $all ?
            Address::where('user_id', $user_id)
                ->select($columns)
                ->get()
                ->toArray()
            :
            Address::where('id', $check)
                ->select($columns)
                ->get()
                ->toArray()[0];
    }

    public static function getAddressList($user_id)
    {
        $baseInfos = Address::getBaseInfo($user_id);
        $addressList = [];
        foreach ($baseInfos as $baseInfo) {
            $baseInfo['district'] = Address::getDistrictByThirdId($baseInfo['third_level']);
            unset ($baseInfo['third_level']);
            array_push($addressList, $baseInfo);
        }

        return $addressList;
    }

    /**
     * 刷新默认收货地址
     * @param $id
     * @param $bool
     */
    public static function refreshDefault($id, $bool)
    {
        DB::table('addresses')->update(['default' => false]);
        Address::find($id)->update(['default' => $bool]);
    }
}